package com.cskaoyan.wordmemorize.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cskaoyan.wordmemorize.common.constant.ResultCodeEnum;
import com.cskaoyan.wordmemorize.common.exception.ExcelParseException;
import com.cskaoyan.wordmemorize.dao.entity.VocChapBookDO;
import com.cskaoyan.wordmemorize.dao.entity.VocExcelParsedDO;
import com.cskaoyan.wordmemorize.dao.mapper.VocChapBookMapper;
import com.cskaoyan.wordmemorize.dao.mapper.VocMapper;
import com.cskaoyan.wordmemorize.dto.admin.VocExcelDTO;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class VocExcelListener implements ReadListener<VocExcelDTO> {


     VocMapper vocMapper;
     VocChapBookMapper vocChapBookMapper;
     String INTERPRETATION_REGEX = "^.+\\..+$";

    public VocExcelListener(VocMapper vocMapper, VocChapBookMapper vocChapBookMapper) {
        this.vocMapper = vocMapper;
        this.vocChapBookMapper = vocChapBookMapper;
    }

    @Override
    public void invoke(VocExcelDTO data, AnalysisContext context) {
        int rowIndex = context.readRowHolder().getRowIndex() + 1; // Excel行号从2开始

        // 1. 校验基本字段非空
        checkNotNull(data.getContent(), rowIndex, 1, "单词不能为空");
        checkNotNull(data.getInterpretations(), rowIndex, 6, "释义不能为空");
        checkNotNull(data.getBookInfos(), rowIndex, 8, "书籍章节信息不能为空");

        // 2. 校验单词释义格式 (支持多行多释义)
        String[] interpretations = data.getInterpretations().split("\n");
        for (int i = 0; i < interpretations.length; i++) {
            String interpretation = interpretations[i];
            if (!interpretation.matches(INTERPRETATION_REGEX)) {
                throw new ExcelParseException(
                        ResultCodeEnum.FAIL,
                        rowIndex,
                        6,
                        interpretation,
                        "第" + (i + 1) + "个释义格式应为'词性.词义'"
                );
            }
        }

        // 3. 校验例句格式 (支持多行多例句)
        if (data.getExampleSentences() != null) {
            String[] lines = data.getExampleSentences().split("\n");

            // 检查行数是否为偶数(英文+中文成对)
            if (lines.length % 2 != 0) {
                throw new ExcelParseException(
                        ResultCodeEnum.FAIL,
                        rowIndex,
                        7,
                        data.getExampleSentences(),
                        "例句总行数应为偶数(英文和中文成对出现)"
                );
            }

            // 检查每对例句格式
            for (int i = 0; i < lines.length; i += 2) {
                String english = lines[i];
                String chinese = lines[i + 1];

                // 检查英文例句是否为空
                if (english == null || english.trim().isEmpty()) {
                    throw new ExcelParseException(
                            ResultCodeEnum.FAIL,
                            rowIndex,
                            7,
                            null,
                            "第" + ((i/2) + 1) + "组例句的英文部分不能为空"
                    );
                }

                // 检查中文翻译是否为空
                if (chinese == null || chinese.trim().isEmpty()) {
                    throw new ExcelParseException(
                            ResultCodeEnum.FAIL,
                            rowIndex,
                            7,
                            null,
                            "第" + ((i/2) + 1) + "组例句的中文部分不能为空"
                    );
                }
            }
        }

        // 4. 校验书籍章节存在性
        String[] parts = data.getBookInfos().split("#", 2);
        if (parts.length != 2) {
            throw new ExcelParseException(
                    ResultCodeEnum.FAIL,
                    rowIndex,
                    8,
                    data.getBookInfos(),
                    "书籍章节格式应为'书籍#章节'"
            );
        }

        String bookName = parts[0];
        String chapterName = parts[1];

        // 检查书籍是否存在
        QueryWrapper<VocChapBookDO> bookWrapper = new QueryWrapper<>();
        bookWrapper.eq("book_name", bookName);
        if (!vocChapBookMapper.exists(bookWrapper)) {
            throw new ExcelParseException(
                    ResultCodeEnum.FAIL,
                    rowIndex,
                    8,
                    bookName,
                    "书籍不存在"
            );
        }

        // 章节存在性校验
        if (chapterName != null && !chapterName.isEmpty()) {
            QueryWrapper<VocChapBookDO> chapterWrapper = new QueryWrapper<>();
            chapterWrapper.eq("book_name", bookName)
                    .eq("chapter_name", chapterName);
            if (!vocChapBookMapper.exists(chapterWrapper)) {
                throw new ExcelParseException(
                        ResultCodeEnum.FAIL,
                        rowIndex,
                        8,
                        chapterName,
                        "章节不存在"
                );
            }
        }
    }

    @Override
    public boolean hasNext(AnalysisContext context) {
        // 发生异常时自动终止读取，无需手动控制
        return ReadListener.super.hasNext(context);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("Excel文件校验完成");
    }
    // 辅助方法：检查字段非空
    private void checkNotNull(Object value, int rowNum, int colNum, String message) {
        if (value == null) {
            throw new ExcelParseException(
                    ResultCodeEnum.FAIL,
                    rowNum,
                    colNum,
                    null,
                    message
            );
        }
    }
}
